#!/usr/bin/env eco

local workqueue = require 'workqueue'
local time = require 'eco.time'

-- 使用默认系统队列
local sys_queue = workqueue.sys_queue

-- 创建自定义工作队列
local my_queue = workqueue.new()
my_queue:start(2)  -- 启动2个工作线程

-- 任务函数定义
local function process_data(data, priority)
    print(string.format("[%s] Processing data: %s (priority: %d)", os.date("%X"), data, priority))
    time.sleep(1)
    print(string.format("[%s] Finished processing: %s", os.date("%X"), data))
end

local function send_email(to, subject, body)
    print(string.format("[%s] Sending email to: %s", os.date("%X"), to))
    time.sleep(2)
    print(string.format("[%s] Email sent: %s - %s", os.date("%X"), subject, body))
end

local function base_test()
    print(string.format("[%s] Test No Param", os.date("%X")))
end

local function urgent_test()
    print(string.format("[%s] Test Urgent Msg", os.date("%X")))
end

local function timed_task()
    print(string.format("[%s] This is a timed task", os.date("%X")))
end

-- 向系统队列添加任务
print("Adding tasks to system queue...")
local task1 = sys_queue:add_task(process_data, "user_data.csv", 1)
local task2 = sys_queue:add_task(send_email, "admin@example.com", "Report", "Monthly report attached")
local task3 = sys_queue:add_task(process_data, "logs.txt", 2)
local task4 = sys_queue:add_task(send_email, "user@example.com", "Welcome", "Welcome to our service!")

print("Adding urgent task to system queue...")
local urgent_task = sys_queue:add_urgent_task(urgent_test)

print("Adding timed task to system queue...")
local timed_task_handle = sys_queue:add_task_time(timed_task, 5)

-- 向自定义队列添加任务
print("Adding tasks to custom queue...")
local my_task1 = my_queue:add_task(process_data, "custom_data_1.csv", 3)
local my_task2 = my_queue:add_task(send_email, "custom@example.com", "Custom Report", "Custom content")
local my_task3 = my_queue:add_task(process_data, "custom_logs.txt", 4)

print("Adding timed task to custom queue...")
local my_timed_task = my_queue:add_task_time(timed_task, 3)

-- 取消一个任务
print("Canceling task3 in system queue...")
sys_queue:cancel_task(task3)

-- 等待一段时间让任务执行
time.sleep(8)

-- 显示队列状态
print("\nSystem queue status:")
local sys_status = sys_queue:get_status()
print(string.format("  Normal tasks: %d, Timed tasks: %d, Total handles: %d, Running: %s",
    sys_status.normal_tasks, sys_status.timed_tasks, sys_status.active_handles, tostring(sys_status.running)))

print("Custom queue status:")
local my_status = my_queue:get_status()
print(string.format("  Normal tasks: %d, Timed tasks: %d, Total handles: %d, Running: %s",
    my_status.normal_tasks, my_status.timed_tasks, my_status.active_handles, tostring(my_status.running)))

-- 停止自定义队列
my_queue:stop()
print("Custom queue stopped")

-- 继续等待系统队列完成任务
time.sleep(5)

-- 停止系统队列
sys_queue:stop()
print("System queue stopped")
print("All tasks completed or canceled")